﻿
CREATE PROCEDURE [dbo].[CalcDisponibilOrdRows]  
	@IDClasificare int, 
	@Analitic TipCont,
	@PanaLa DateTime,
	@CodDoc int,
	@CodUnitate smallint
AS 
begin
	DECLARE @strEroare AS varchar(200)

	DECLARE @cont TipCont
	DECLARE @cont2 TipCont

	SET @cont ='8062.'+@Analitic
	SET @cont2 ='7701.'+@Analitic
	SELECT NumarDoc, DataDoc, coalesce(r.ValoareLei,0) ValoareLeiDebit, 0  ValoareLeiCredit, ContDebit Cont FROM Rulaje r
	JOIN RulajeDoc d ON r.IDDocument = d.IDDocument AND IDJurnal = @IDClasificare AND d.[CodUnitate] = @CodUnitate AND (d.DataDoc<=@PanaLa)  
	WHERE  ContDebit=@cont
    UNION		
	SELECT NumarDoc, DataDoc, 0 ValoareLeiDebit, coalesce(r.ValoareLei,0) ValoareLeiCredit, ContCredit Cont FROM Rulaje r
	JOIN RulajeDoc d ON r.IDDocument = d.IDDocument AND
		IDJurnal = @IDClasificare  AND d.[CodUnitate] = @CodUnitate AND (d.DataDoc<=@PanaLa) 
	WHERE ContCredit=@cont
	--@totDebitPla	
	UNION
	SELECT NumarDoc, DataDoc,coalesce(r.ValoareLei,0) ValoareLeiDebit, 0 ValoareLeiCredit, ContDebit Cont FROM [Rulaje] r 
	JOIN RulajeDoc d ON  r.IDDocument = d.IDDocument AND
		IDJurnal = @IDClasificare AND d.[CodUnitate] = @CodUnitate AND DataDoc<@PanaLa
	WHERE ContDebit= @cont2 AND r.TipDocJust<>'IC'
    --@totCreditPla
    UNION
	SELECT NumarDoc, DataDoc,0 ValoareLeiDebit, coalesce(r.ValoareLei,0) ValoareLeiCredit, ContCredit Cont FROM [Rulaje] r 
	JOIN RulajeDoc d ON r.IDDocument = d.IDDocument AND
		 IDJurnal = @IDClasificare AND d.[CodUnitate] = @CodUnitate AND DataDoc<@PanaLa
    WHERE ContCredit=@cont2 AND r.TipDocJust<>'IC'
    --@totOrdonantat
    UNION
	SELECT NrDoc, DataDoc,0 ValoareLeiDebit, coalesce(ValoareLei,0) ValoareLeiCredit, 'ORDONANTARE' Cont FROM [Ordonantari] WHERE  (DataDoc<@PanaLa 
			OR (DataDoc=@PanaLa  AND IDOrdonantare<@CodDoc)) AND ArtAl Like @Analitic+'%'
			AND IDJurnal=@IDClasificare AND [CodUnitate] = @CodUnitate AND Achitat=0	
	ORDER BY DataDoc
	--SET @s944 = @totDebit + @totDebitPla - @totCredit - @totCreditPla - @totOrdonantat
    --PRINT (@totOrdonantat)


	 GOTO Gata
Eroare:
	 RAISERROR (@strEroare,16,-1)
Gata:
end